package com.writing.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.writing.controller.ImageGenerationController.ImageGenerationRequest;
import com.writing.controller.ImageGenerationController.ImageGenerationResponse;
import com.writing.controller.ImageGenerationController.ImageData;
import com.writing.entity.ApiConfig;
import com.writing.service.ApiConfigService;
import com.writing.service.ImageGenerationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 图像生成服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ImageGenerationServiceImpl implements ImageGenerationService {

    private final ApiConfigService apiConfigService;
    private final RestTemplate restTemplate = new RestTemplate();

    @Override
    public ImageGenerationResponse generateImage(ImageGenerationRequest request, Long userId) {
        try {
            // 获取启用的API配置（优先使用公共配置）
            List<ApiConfig> configs = apiConfigService.getEnabledConfigs();
            if (configs.isEmpty()) {
                throw new RuntimeException("未找到可用的API配置");
            }

            // 使用第一个启用的配置
            ApiConfig config = configs.get(0);
            String baseUrl = config.getBaseUrl();
            String apiKey = config.getApiKey();
            
            // 规范化baseUrl，移除末尾斜杠
            baseUrl = baseUrl.trim();
            while (baseUrl.endsWith("/")) {
                baseUrl = baseUrl.substring(0, baseUrl.length() - 1);
            }
            
            // 构建API URL，避免重复的/v1
            String endpoint = "/v1/images/generations";
            String apiUrl;
            if (baseUrl.endsWith("/v1")) {
                // 如果baseUrl已经以/v1结尾，直接拼接剩余路径
                apiUrl = baseUrl + endpoint.substring(3); // 跳过 "/v1"
            } else {
                // 否则完整拼接
                apiUrl = baseUrl + endpoint;
            }

            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", request.getModel());
            requestBody.put("prompt", request.getPrompt());
            requestBody.put("aspect_ratio", request.getAspectRatio());
            requestBody.put("response_format", request.getResponseFormat());
            
            if (request.getImage() != null && !request.getImage().isEmpty()) {
                requestBody.put("image", request.getImage());
            }

            // 构建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + apiKey);

            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

            log.info("调用图像生成API: {}", apiUrl);
            log.info("请求参数: {}", JSON.toJSONString(requestBody));

            // 发送请求
            ResponseEntity<String> response;
            try {
                response = restTemplate.exchange(
                        apiUrl,
                        HttpMethod.POST,
                        entity,
                        String.class
                );
            } catch (HttpClientErrorException e) {
                // 4xx 错误
                String errorBody = e.getResponseBodyAsString();
                log.error("API调用失败 (4xx): {}", errorBody);
                throw new RuntimeException("API调用失败: " + errorBody);
            } catch (HttpServerErrorException e) {
                // 5xx 错误
                String errorBody = e.getResponseBodyAsString();
                log.error("API调用失败 (5xx): {}", errorBody);
                throw new RuntimeException("API服务器错误: " + errorBody);
            } catch (RestClientException e) {
                // 其他网络错误
                log.error("API调用失败: {}", e.getMessage(), e);
                throw new RuntimeException("API调用失败: " + e.getMessage());
            }

            if (response.getStatusCode() != HttpStatus.OK) {
                throw new RuntimeException("API调用失败，状态码: " + response.getStatusCode());
            }

            // 解析响应
            String responseBody = response.getBody();
            log.info("API响应: {}", responseBody);

            JSONObject jsonResponse = JSON.parseObject(responseBody);
            JSONArray dataArray = jsonResponse.getJSONArray("data");

            ImageGenerationResponse result = new ImageGenerationResponse();
            List<ImageData> imageDataList = new ArrayList<>();

            if (dataArray != null) {
                for (int i = 0; i < dataArray.size(); i++) {
                    JSONObject item = dataArray.getJSONObject(i);
                    ImageData imageData = new ImageData();
                    
                    if (item.containsKey("url")) {
                        imageData.setUrl(item.getString("url"));
                    }
                    if (item.containsKey("b64_json")) {
                        imageData.setB64Json(item.getString("b64_json"));
                    }
                    
                    imageDataList.add(imageData);
                }
            }

            result.setData(imageDataList);
            return result;

        } catch (Exception e) {
            log.error("图像生成失败", e);
            throw new RuntimeException("图像生成失败: " + e.getMessage(), e);
        }
    }
}

